/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.application.impl.channel;

import java.util.Collection;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.foreveross.bsl.push.application.impl.DsRouterGroupPushs;
import com.foreveross.bsl.push.application.impl.DsRouterHelper;
import com.foreveross.bsl.push.application.impl.DsRouterPushId;
import com.foreveross.bsl.push.domain.entity.Push;
import com.foreveross.bsl.push.repository.PushRepository;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-9-3
 *
 */
@Component
public class DefaultSendFeedbacker implements SendFeedbackable {
	
	final static Logger log = LoggerFactory.getLogger(DefaultSendFeedbacker.class);
	
	private final PushRepository getPushRepository(){
		return new Push().getEntityRepository(PushRepository.class);
	}
	
	@Override
	public void sentSuccessfully(Date sentTime, DsRouterPushId... pushIds) {
		Assert.notEmpty(pushIds, "pushIds must not be empty!");
		Collection<DsRouterGroupPushs> pushList=DsRouterGroupPushs.group(pushIds);
		for(DsRouterGroupPushs dr : pushList){
			DsRouterHelper.setCurrentDsRouter(dr.getDsRouter());
			getPushRepository().findAndUpdateToSentByIds(sentTime, dr.getPushIds());
		}
	}

	@Override
	public void communicationFailure(String msg, Throwable e, DsRouterPushId... pushIds) {
		Assert.notEmpty(pushIds, "pushIds must not be empty!");
		log.error(msg, e);
		Collection<DsRouterGroupPushs> pushList=DsRouterGroupPushs.group(pushIds);
		for(DsRouterGroupPushs dr : pushList){
			DsRouterHelper.setCurrentDsRouter(dr.getDsRouter());
			getPushRepository().findAndUpdateToOfflineByIds(dr.getPushIds(), msg);
		}
	}

	@Override
	public void unrecoverableFailure(String msg, Throwable e, DsRouterPushId... pushIds) {
		Assert.notEmpty(pushIds, "pushIds must not be empty!");
		log.error(msg, e);
		Collection<DsRouterGroupPushs> pushList=DsRouterGroupPushs.group(pushIds);
		for(DsRouterGroupPushs dr : pushList){
			DsRouterHelper.setCurrentDsRouter(dr.getDsRouter());
			getPushRepository().findAndUpdateToFailureByIds(dr.getPushIds(), msg);
		}
	}
	
	@Override
	public void couldRetryFailure(String msg, Throwable e, DsRouterPushId... pushIds) {
		Assert.notEmpty(pushIds, "pushIds must not be empty!");
		log.error(msg, e);
		//TODO need to add retry strategy
		Collection<DsRouterGroupPushs> pushList=DsRouterGroupPushs.group(pushIds);
		for(DsRouterGroupPushs dr : pushList){
			DsRouterHelper.setCurrentDsRouter(dr.getDsRouter());
			getPushRepository().findAndUpdateToFailureByIds(dr.getPushIds(), msg);
		}
	}

}
